import axios from "axios";
import { message } from "ant-design-vue";

import router from "@/router";

let option = {
  isMessage: true,
};
// 创建axios实例
const instance = axios.create({
  // 服务接口请求
  baseURL: "https://55t1199g09.zicp.fun",
  //   baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时设置
  timeout: 15000,
});

instance.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("token")) {
      config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    }

    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

instance.interceptors.response.use(
  (res) => {
    // token过期
    if (res.data.status === 20) {
      router.push("/login");
    }

    if (res.data.status === 1) {
    } else {
      if (option.isMessage) message.error(res.data.message);
    }

    return res;
  },
  (err) => {
    message.error(err.message);
    return Promise.reject(err);
  }
);
export default instance;

export async function corsApi(  url: string,  methodType: string,  data: any,  options: any = { isMessage: true }) {
  option.isMessage = options.isMessage;
  const config: any = {
    url,
    method: methodType,
  };

  if (methodType === "get" || methodType === "GET") {
    config.params = data;
  } else {
    config.data = data;
  }

  return await instance(config);
}
